package cn.cxy.notepad.ui

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import cn.cxy.notepad.ExtraKey
import cn.cxy.notepad.R
import cn.cxy.notepad.db.bean.Note
import cn.cxy.notepad.db.repository.NoteRepository
import kotlinx.android.synthetic.main.activity_edit_note.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * 新增笔记
 */
class AddNoteActivity : AppCompatActivity() {
    protected var noteRepository = NoteRepository()
    protected var note: Note? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_note)
        note = intent?.getParcelableExtra(ExtraKey.KEY_NOTE)
        initViews()
        initListeners()
    }

    private fun saveNote(content: String) {
        GlobalScope.launch {
            noteRepository.add(content)
        }
    }

    private fun initViews() {
        listNoteToolbar.inflateMenu(R.menu.edit_note_menu)
        listNoteToolbar.setNavigationOnClickListener {
            saveNoteAndFinish()
        }
    }

    private fun initListeners() {
        listNoteToolbar.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.submitNoteMenuItem -> saveNoteAndFinish()
            }
            false
        }
    }

    private fun saveNoteAndFinish() {
        if (contentET.text.toString().isNotBlank()) {
            saveNote(contentET.text.toString())
        }
        finish()
    }
}
